package com.winit.cloudlink.message.internal.rabbitmq;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.MessageListener;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.messaging.support.GenericMessage;

import com.winit.cloudlink.message.Message;
import com.winit.cloudlink.message.MessageEngine;
import com.winit.cloudlink.message.handler.MessageHandler;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Created by stvli on 2015/11/10.
 */
@SuppressWarnings("rawtypes")
public class MessageAdapterHandler implements MessageListener {

	private final Logger         logger = LoggerFactory.getLogger(MessageAdapterHandler.class);
	private final MessageEngine  messageEngine;
	private final MessageHandler messageHandler;

	private MessageConverter     messageConverter;                                             // 直接指定

	public MessageAdapterHandler(MessageEngine messageEngine, MessageHandler messageHandler,
								 MessageConverter messageConverter){
		this.messageEngine = messageEngine;
		this.messageHandler = messageHandler;
		this.messageConverter = messageConverter;
	}

	@SuppressWarnings("unchecked")
	@Override
	public void onMessage(org.springframework.amqp.core.Message message) {
		Message targetMessage = buildMessage(message);
		messageHandler.process(targetMessage);
		httpRequest("http://127.0.0.1:8097/api/v1/clQueue/cloudLinkRtn?id="+targetMessage.getHeaders().getMessageId(),"GET",null);
	}


	public static String httpRequest(String requestUrl,String requestMethod,String outputStr){
		StringBuffer buffer=null;
		try{
			URL url=new URL(requestUrl);
			HttpURLConnection conn=(HttpURLConnection)url.openConnection();
			conn.setDoOutput(true);
			conn.setDoInput(true);
			conn.setRequestMethod(requestMethod);
			conn.connect();
			//往服务器端写内容 也就是发起http请求需要带的参数
			if(null!=outputStr){
				OutputStream os=conn.getOutputStream();
				os.write(outputStr.getBytes("utf-8"));
				os.close();
			}

			//读取服务器端返回的内容
			InputStream is=conn.getInputStream();
			InputStreamReader isr=new InputStreamReader(is,"utf-8");
			BufferedReader br=new BufferedReader(isr);
			buffer=new StringBuffer();
			String line=null;
			while((line=br.readLine())!=null){
				buffer.append(line);
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		return buffer.toString();
	}

	private Message buildMessage(org.springframework.amqp.core.Message originalMessage) {
		GenericMessage genericMessage = (GenericMessage) messageConverter.fromMessage(originalMessage);
		Message message = new Message(genericMessage);
		return message;
	}
}